﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
//using JsonSerializer = ServiceStack.Text.JsonSerializer;

namespace CSS.Common
{
    public class NewtonJson
    {
        // Serialize
        public static string Serialize(object @object, string dateTimeFormat)
        {
            try
            {
                return JsonConvert.SerializeObject(@object, new IsoDateTimeConverter { DateTimeFormat = dateTimeFormat });
                //return JsonSerializer.SerializeToString(@object);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static string Serialize(object @object)
        {
            try
            {
                return JsonConvert.SerializeObject(@object, MicrosoftDateFormatSettings);
                //return JsonSerializer.SerializeToString(@object);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        // DeSerialize
        public static T Deserialize<T>(string jsonString)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonString, MicrosoftDateFormatSettings);
                //return JsonSerializer.DeserializeFromString<T>(jsonString);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        public static T Deserialize<T>(string jsonString, string dateTimeFormat)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonString, new IsoDateTimeConverter { DateTimeFormat = dateTimeFormat });
                //return JsonSerializer.DeserializeFromString<T>(jsonString);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        // Privates Format Date
        private static readonly JsonSerializerSettings MicrosoftDateFormatSettings = new JsonSerializerSettings
                                                                         {
                                                                             DateFormatHandling =
                                                                                 DateFormatHandling.MicrosoftDateFormat
                                                                         };
    }
}
